package per.kongtouxu.controller;

import org.apache.commons.beanutils.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import per.kongtouxu.Util.CommonMethod;
import per.kongtouxu.domain.dto.JsonDto;
import per.kongtouxu.domain.pojo.Admin;
import per.kongtouxu.domain.pojo.AdminLog;
import per.kongtouxu.domain.pojo.Menu;
import per.kongtouxu.domain.pojo.PageBean;
import per.kongtouxu.domain.vo.V_Admin;
import per.kongtouxu.service.AdminService;
import per.kongtouxu.service.MenuService;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/admin")
public class AdminController {
    @Autowired
    private AdminService adminService;
    @Autowired
    private MenuService service ;

    //用户登录
    @RequestMapping("/adminLogin")
    public @ResponseBody JsonDto adminLogin(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        System.out.println("开始匹配验证码!!");
        //1.获取页面传来的检验码
        String check = req.getParameter("check");
        //2.从session中获取验证码
        HttpSession session = req.getSession();
        String checkcode_server = (String) session.getAttribute("CHECKCODE_SERVER");
        session.removeAttribute("CHECKCODE_SERVER");//为了保证验证码只能使用一次
        //2.2用于返回的信息
        JsonDto info = new JsonDto();
        //3.比较验证码
        if (checkcode_server == null || !checkcode_server.equalsIgnoreCase(check)) {
            System.out.println(check);
            System.out.println(checkcode_server);
            //验证码错误
            //1.注册失败
            info.setId(0);
            info.setMessage("验证码错误！！");
            //2.将info对象序列化为Json
            return info;
        }
        //1.获取用户名和密码数据
        Map<String, String[]> map = req.getParameterMap();
        //2.封装User对象
        Admin admin = new Admin();
        try {
            BeanUtils.populate(admin, map);
            System.out.println("自动封装之后的bean：" + admin);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        //3.调用service查询
        Admin loginAdmin = adminService.login(admin);
        System.out.println("查询后的后台用户：" + loginAdmin);
        //4.判断用户是否为空
        if (loginAdmin == null) {
            //用户名密码错误
            info.setId(0);
            info.setMessage("用户名密码错误！！");
        } else {
            //用户名正确
            info.setId(1);
            info.setMessage("登录成功！！");
            info.setLocation("index");
            System.out.println("登录成功");
            req.getSession().setAttribute("loginAdmin", loginAdmin);
        }
        //5.响应数据

        return info;
    }

    /**
     * 查询登录的用户，并返回菜单
     *
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    @RequestMapping("/findloginAdmin")
    public @ResponseBody HashMap<String, Object> findloginAdmin(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1.从session中获取登录用户
        Admin loginAdmin = (Admin) req.getSession().getAttribute("loginAdmin");
        //2.查询菜单
        Integer adminId = Math.toIntExact(loginAdmin.getAdminId());
        List<Menu> menuList = service.findMenuByAdminId(adminId);
        //3.map
        HashMap<String, Object> map = new HashMap<>();
        map.put("loginAdmin", loginAdmin);
        map.put("menuList", menuList);
        return map;
    }


    //删除session
    @RequestMapping("/deleteLoginAdminSession")
    public @ResponseBody Boolean deleteLoginAdminSession(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //删除session
        // req.getSession().invalidate();
        req.getSession().removeAttribute("loginAdmin");
        return true;
    }

    //分页查询
    @RequestMapping("/findAdminByPage")
    public @ResponseBody PageBean<V_Admin> findAdminByPage(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1.获取参数
        String adminName = req.getParameter("adminName");
        String roleId = req.getParameter("roleId");
        String startTime = req.getParameter("startTime");
        String endTime = req.getParameter("endTime");
        String currentPage = req.getParameter("currentPage");
        String pageSize = req.getParameter("pageSize");
        //2.查询service
        PageBean<V_Admin> vAdminList = adminService.findAdminByPage(adminName, Integer.parseInt(roleId), startTime, endTime, Integer.parseInt(currentPage), Integer.parseInt(pageSize));
        //3.发送JSON
        return vAdminList;
    }

    //保存用户
    @RequestMapping("/saveAdmin")
    public @ResponseBody Integer saveAdmin(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1.获取参数
        Map<String, String[]> map = req.getParameterMap();
        //2.封装
        Admin admin = new Admin();
        try {
            BeanUtils.populate(admin, map);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        System.out.println("得到后的管理员:" + admin);
        //2.后台日志插入
        AdminLog adminLog = CommonMethod.getAdminLog(req);
        adminLog.setDoName("添加后台管理员");
        //3.调用service
        Integer result = adminService.saveAdmin(admin, adminLog);
        //4.返回
        return result;
    }

    //禁用启用
    @RequestMapping("/banPick")
    public @ResponseBody Integer banPick(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1.获取参数
        Map<String, String[]> map = req.getParameterMap();
        //2.封装
        Admin admin = new Admin();
        try {
            BeanUtils.populate(admin, map);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        System.out.println("得到后的管理员:" + admin);
        //2.后台日志插入
        AdminLog adminLog = CommonMethod.getAdminLog(req);
        String stateName = req.getParameter("stateName");
        if (stateName.equals("启用")) {
            //设置日志
            adminLog.setDoName("禁用后台用户");
            admin.setAdminState(2);
        } else if (stateName.equals("禁用")) {
            adminLog.setDoName("启用后台用户");
            admin.setAdminState(1);
        }
        //3.调用service
        Integer result = adminService.updateAdmin(admin, adminLog);
        //4.返回
        return result;
    }

    //修改密码
    @RequestMapping("/updatePwd")
    public @ResponseBody Integer updatePwd(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1.获取参数
        Map<String, String[]> map = req.getParameterMap();
        //2.封装
        Admin admin = new Admin();
        try {
            BeanUtils.populate(admin, map);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        System.out.println("得到后的管理员:" + admin);
        //2.后台日志插入
        AdminLog adminLog = CommonMethod.getAdminLog(req);
        adminLog.setDoName("修改后台用户密码");
        //3.调用service
        Integer result = adminService.updateAdmin(admin, adminLog);
        //4.返回
        return result;
    }
    //根据AdminId查询Admin
    @RequestMapping("/findAdminByAdminId")
    public @ResponseBody Admin findAdminByAdminId(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1.获取
        String adminId = req.getParameter("adminId");
        System.out.println("adminId:"+adminId);
        //2.查询service
        Admin admin = adminService.findAdminByAdminId(Integer.parseInt(adminId));
        //3.发送JSON
        return admin;
    }
    //更新用户
    @RequestMapping("/updateAdminInfo")
    public @ResponseBody Integer updateAdminInfo(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1.获取参数
        Map<String, String[]> map = req.getParameterMap();
        //2.封装
        Admin admin = new Admin();
        try {
            BeanUtils.populate(admin, map);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        System.out.println("得到后的管理员:" + admin);
        //2.后台日志插入
        AdminLog adminLog = CommonMethod.getAdminLog(req);
        adminLog.setDoName("修改后台用户");
        //3.调用service
        Integer result = adminService.updateAdmin(admin, adminLog);
        //4.返回
        return result;
    }


}
